package moltencore.network.protocol;

import spark.network.Util;
import spark.network.protocol.Base;

public class Login extends Base {
	public static final short TYPE = 0x10;
	private static final byte[] TYPE_BYTES = Util.makeBytes(TYPE);

	public static final int NAME_LENGTH_MAX = 12;

	/**
	 * length of the players name
	 */
	private byte nameLength;
	private static final int NAME_LENGTH_OFFSET = Base.SIZE;
	private static final int NAME_LENGTH_LENGTH = Byte.SIZE / 8;

	/**
	 * nickname with whitch the player logs in
	 */
	private byte[] name;
	private static final int NAME_OFFSET = NAME_LENGTH_OFFSET + NAME_LENGTH_LENGTH;

	private static final int SIZE =
			Base.SIZE +
	        NAME_LENGTH_LENGTH;

	public Login() {
		super(true, TYPE_BYTES);
	}

	public String getName() {
		return name == null ? null : new String(name);
	}

	public void setName(String name) {
		if(name != null) {
			byte[] nameBytes = name.getBytes();
			//set the length of the name to the length of the provided string or to the maximal allowed length if the strings
			//length exceeds the maximum length
			nameLength = (byte)((nameBytes.length > NAME_LENGTH_MAX) ? NAME_LENGTH_MAX : nameBytes.length);

			//write nameLength characters into the name byte array
			this.name = new byte[nameLength];
			System.arraycopy(nameBytes, 0, this.name, 0, nameLength);
		}
		else {
			nameLength = 0;
		}
	}

	@Override
	public void getBytes(byte[] buffer) {
		super.getBytes(buffer);
		buffer[NAME_LENGTH_OFFSET] = nameLength;
		if(name != null) {
			Util.arraycopy(name, 0, buffer, NAME_OFFSET, nameLength);
		}
	}

	@Override
	public void fill(byte[] buffer) {
		super.fill(buffer);
		nameLength = buffer[NAME_LENGTH_OFFSET];
		if(nameLength > 0) {
			name = new byte[nameLength];
			Util.arraycopy(buffer, NAME_OFFSET, name, 0, nameLength);
		}
	}

	@Override
	public int getSize() {
		return SIZE + nameLength;
	}

	public static Login create(byte[] buffer, long receiveTime) {
		Login packet = new Login();
		packet.fill(buffer);
		packet.setTimeStampReceive(receiveTime);
		return packet;
	}
}
